package com.demo;

import java.util.Properties;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.cloud.nacos.NacosServiceManager;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.listener.Event;
import com.alibaba.nacos.api.naming.listener.EventListener;
import com.alibaba.nacos.api.naming.listener.NamingEvent;

@RestController
@RefreshScope
public class ManagerController {
	
	// 使用原生注解@Value()导入配置
    @Value("${name:zsl}")
    private String name;
    @Autowired
	private NacosServiceManager nacosServiceManager;
    
    @GetMapping("getcfg")
    public String providerTest() {
        return "我是provider，已成功获取nacos配置中心的数据：(name:" + name +")";
    }

	@GetMapping("/dereg")
	public boolean dereg() throws Exception {
		NamingService naming2 =  nacosServiceManager.getNamingService(null);
        naming2.subscribe("nacosDemo", new EventListener() {
            @Override
            public void onEvent(Event event) {
                System.out.println(((NamingEvent)event).getServiceName());
                System.out.println(((NamingEvent)event).getInstances());
            }
        });
		
		Properties properties = new Properties();
        properties.setProperty("serverAddr", System.getProperty("serverAddr"));
        properties.setProperty("namespace", System.getProperty("namespace"));
        NamingService naming = NamingFactory.createNamingService(properties);

        naming.registerInstance("nacosDemo", "11.11.11.11", 8888, "TEST1");

        naming.registerInstance("nacosDemo", "2.2.2.2", 9999, "DEFAULT");

        System.out.println(naming.getAllInstances("nacosDemo"));

        naming.deregisterInstance("nacosDemo", "2.2.2.2", 9999, "DEFAULT");

        System.out.println(naming.getAllInstances("nacosDemo"));

        return true;
	}
}